USE [wdms]
GO

-- =============================================
-- Author     :		Lohith Ram D V
-- Create date:         08/mar/2011
-- =============================================

create procedure sp_ShareDocument(
	@par_docid int,
	@par_user_originid int,
	@par_user_targetid int,
	@par_read binary,
	@par_update binary,
	@par_check binary)
AS
BEGIN
	
	IF EXISTS(SELECT * FROM [Doc_Share] WHERE [Doc_Share].[user_origin_id]=@par_user_originid 
	AND [Doc_Share].[user_target_id]=@par_user_targetid AND
	[Doc_Share].[doc_id]=@par_docid)
		RETURN 0;
		
	BEGIN
		IF EXISTS(SELECT [Document].[doc_id] FROM [Document] WHERE [Document].[doc_id]=@par_docid AND [Document].[user1_id]=@par_user_originid)
		BEGIN 

			INSERT INTO [Doc_Share]([Doc_Share].[doc_id], [Doc_Share].[user_origin_id], [Doc_Share].[user_target_id], [Doc_Share].[sh_read], [Doc_Share].[sh_update], [Doc_Share].[sh_check])
			VALUES (@par_docid, @par_user_originid, @par_user_targetid, @par_read, @par_update, @par_check)
		    
			DECLARE @targetdept int
			SELECT @targetdept = (SELECT [User1_Dept].[dept_id]
			FROM  [User1_Dept]
			WHERE @par_user_targetid=[User1_Dept].[user1_id])
		    
			INSERT INTO [Doc_Dept]([Doc_Dept].[doc_id], [Doc_Dept].[dept_id])
			VALUES (@par_docid, @targetdept)
			RETURN 1;
		END
	END 
END
